
from django.shortcuts import render, redirect, HttpResponse
from mardan import models
from mardan.utils.form import UserModelForm, AdminModelForm, CategoryModelForm, GoodsModelForm, OrderModelForm
from mardan.utils.pagination import Pagination
from datetime import datetime,timedelta


def indexadmin(request):
    """ 返回登录过后的首页 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    return render(request, 'indexadmin.html')


def admininfo(request):
    """ 个人信息 """
    info = request.session.get("info")
    if not info:
        return redirect('/login')
    info_dict = request.session["info"]  # 获取写到数据库的sessin。为了获得当前登录用户的id
    # print("用户id为：{}".format(info_dict["id"]))
    # print("用户名为：{}".format(info_dict["name"]))
    queryset = models.Admin.objects.all().filter(id=info_dict["id"])  # 根据当前的用户id筛选个人数据
    return render(request, "admininfo.html", {"queryset": queryset})


# 找回密码
def zhaohuipwd(request):
    """找回密码"""
    if request.method == "GET":
        return render(request, "zhaohui_mima_admin.html")
    username = request.POST.get("username")
    email = request.POST.get("email")
    pwd = request.POST.get("pwd")
    pwd1 = request.POST.get("pwd1")
    queryset = models.Admin.objects.filter(username=username).values()
    if queryset.count() == 0:
        return redirect('/login')
    querysetemail = models.Admin.objects.filter(username=username).values("email").first()["email"]  # 获取该用户的邮箱
    if email == querysetemail:
        if pwd == pwd1:
            queryset = models.Admin.objects.filter(username=username).values().update(password=pwd)
            return redirect('/adminlogin/')
        if pwd != pwd1:
            return redirect('/zhaohuipwd/admin')
    return redirect('/zhaohuipwd/admin')


def admin_edit(request, nid):
    """ 编辑"""
    info = request.session.get("info")
    if not info:
        return redirect('/login')
    row_object = models.Admin.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = AdminModelForm(instance=row_object)
        return render(request, 'admin_edit.html', {'form': form})

    form = AdminModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/Admin/info/')
    return render(request, 'admin_edit.html', {"form": form})


def admin_delete(request, nid):
    """ 删除管理员 """
    info = request.session.get("info")
    if not info:
        return redirect('/login')
    models.Admin.objects.filter(id=nid).delete()
    # return HttpResponse("成功")
    return redirect("/index/1/")


def admin_useradd(request):
    """ 添加用户 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    if request.method == "GET":
        form = UserModelForm()  # 生成aadmin_useradd.html输入框
        return render(request, 'admin_useradd.html', {"form": form})  # 返回到注册页面
    # 用户POST提交数据，数据校验。
    form = UserModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect('/Admin/userlist/')  # 校验完以后跳转到用户列表页面

    # 校验失败（在页面上显示错误信息）
    return render(request, 'admin_useradd.html', {"form": form})


def admin_userlist(request):
    """ 师生列表 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    ############搜索框的实现#############
    data_dict = {}
    str = ''
    data = models.Admin.objects.filter(username=info["name"]).values()
    for d in data:
        str = d["gname"]
    kuang_data = request.GET.get('q', '')  # 获取框的url和值
    if kuang_data:  # 当框的在用户名包含的时候
        data_dict["username__contains"] = kuang_data
    queryset = models.Yonghu.objects.filter(gname=str, **data_dict)  # 查所有用户信息
    print()
    page_object = Pagination(request, queryset, page_size=8)  # 添加分页功能肄业8条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
        "kuang_data": kuang_data,
    }
    return render(request, "admin_userlist.html", context)


def Admin_user_edit(request, nid):
    """ 编辑用户"""
    row_object = models.Yonghu.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = UserModelForm(instance=row_object)
        return render(request, 'admin_user_edit.html', {'form': form})

    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/Admin/userlist/')
    return render(request, 'admin_user_edit.html', {"form": form})


def Adminuser_delete(request, nid):
    """ 删除用户 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    models.Yonghu.objects.filter(id=nid).delete()
    # return HttpResponse("成功")
    return redirect("/Admin/userlist/")


def admin_categoryadd(request):
    """ 新建分类 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    if request.method == "GET":
        form = CategoryModelForm()
        return render(request, 'admin_categoryadd.html', {"form": form})
    # 用户POST提交数据，数据校验。
    form = CategoryModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect('/Admin/categorylist/')  # 校验完以后跳转到分类列表页面

    # 校验失败（在页面上显示错误信息）
    return render(request, 'admin_categoryadd.html', {"form": form})


def admin_categorylist(request):
    """ 分类列表 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    ############搜索框的实现#############
    data_dict = {}
    kuang_data = request.GET.get('q', '')  # 获取框的url和值
    if kuang_data:  # 当框的在用户名包含的时候
        data_dict["cname__contains"] = kuang_data
    queryset = models.Category.objects.filter(**data_dict)  # 查所有用户信息
    page_object = Pagination(request, queryset, page_size=8)  # 添加分页功能肄业8条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
        "kuang_data": kuang_data,
    }
    return render(request, "admin_categorylist.html", context)


def Admin_category_edit(request, nid):
    """ 编辑分类"""
    row_object = models.Category.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = CategoryModelForm(instance=row_object)
        return render(request, 'admin_category_edit.html', {'form': form})

    form = CategoryModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/Admin/categorylist/')
    return render(request, 'admin_category_edit.html', {"form": form})


def Admincategory_delete(request, nid):
    """ 删除分类 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    models.Category.objects.filter(id=nid).delete()
    # return HttpResponse("成功")
    return redirect("/Admin/categorylist/")


def admin_goodsadd(request):
    """ 新建套餐"""
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    if request.method == "GET":
        form = GoodsModelForm()
        return render(request, 'admin_goodsadd.html', {"form": form})
    # 用户POST提交数据，数据校验。
    form = GoodsModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect('/Admin/goodslist/')  # 校验完以后跳转到商品列表页面
    # 校验失败（在页面上显示错误信息）
    return render(request, 'admin_goodsadd.html', {"form": form})


def admin_goodslist(request):
    """ 套餐列表 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    ############搜索框的实现#############
    data_dict = {}
    str = ''
    print(info["name"])
    data = models.Admin.objects.filter(username=info["name"]).values()
    for d in data:
        str = d["gname"]
    kuang_data = request.GET.get('q', '')  # 获取框的url和值
    if kuang_data:  # 当框的在用户名包含的时候
        data_dict["gname__contains"] = kuang_data
    queryset = models.Goods.objects.filter(gname=str, **data_dict)  # 查所有商品信息
    print(queryset)
    page_object = Pagination(request, queryset, page_size=8)  # 添加分页功能肄业8条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
        "kuang_data": kuang_data,
    }
    return render(request, "admin_goodslist.html", context)


def Admin_goods_edit(request, nid):
    """ 编辑套餐"""
    row_object = models.Goods.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = GoodsModelForm(instance=row_object)
        return render(request, 'admin_goods_edit.html', {'form': form})

    form = GoodsModelForm(data=request.POST, files=request.FILES, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/Admin/goodslist/')
    return render(request, 'admin_goods_edit.html', {"form": form})


def goods_delete(request, nid):
    """ 删除套餐 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    models.Goods.objects.filter(id=nid).delete()
    # return HttpResponse("成功")
    return redirect("/Admin/goodslist/")


def admin_orderlist(request):
    """ 报名列表 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    ############搜索框的实现#############
    data_dict = {}
    str = ''
    # print(info["name"])
    data = models.Admin.objects.filter(username=info["name"]).values()
    for d in data:
        str = d["gname"]
    # print(str)
    kuang_data = request.GET.get('q', '')  # 获取框的url和值
    # print("搜索内容"+kuang_data)
    if kuang_data:  # 当框的在用户名包含的时候
        data_dict["dianhua"] = kuang_data
    print(data_dict)
    queryset = models.Order.objects.filter(gname=str, **data_dict)  # 查所有用户信息
    page_object = Pagination(request, queryset, page_size=5)  # 添加分页功能肄业5条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
        "kuang_data": kuang_data,
    }
    return render(request, "admin_orderlist.html", context)


def admin_orderlistok(request):
<<<<<<< HEAD
    """ 已报名列表 """
=======
    """ 已发货报名列表 """
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    str = ''
    print(info["name"])
    data = models.Admin.objects.filter(username=info["name"]).values()
    for d in data:
        str = d["gname"]
    queryset = models.Order.objects.filter(status=1, gname=str)  # 查所有商品信息
    page_object = Pagination(request, queryset, page_size=5)  # 添加分页功能肄业5条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "admin_orderlistok.html", context)


def admin_orderlistno(request):
<<<<<<< HEAD
    """ 未报名列表 """
=======
    """ 未发货报名列表 """
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    str = ''
    print(info["name"])
    data = models.Admin.objects.filter(username=info["name"]).values()
    for d in data:
        str = d["gname"]
    print(str)
    queryset = models.Order.objects.filter(status=2, gname=str)  # 查所有商品信息
    page_object = Pagination(request, queryset, page_size=5)  # 添加分页功能肄业5条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "admin_orderlistno.html", context)


def admin_orderliststart(request):
<<<<<<< HEAD
    """ 待报名列表 """
=======
    """ 待发货报名列表 """
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    str = ''
    data = models.Admin.objects.filter(username=info["name"]).values()
    for d in data:
        str = d["gname"]
    queryset = models.Order.objects.filter(status=3, gname=str)  # 查所有商品信息
    page_object = Pagination(request, queryset, page_size=5)  # 添加分页功能肄业5条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "admin_orderliststart.html", context)


def Admin_order_edit(request, nid):
    """ 编辑报名"""
    row_object = models.Order.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = OrderModelForm(instance=row_object)
        return render(request, 'admin_order_edit.html', {'form': form})

    form = OrderModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/Admin/orderlist/')
    return render(request, 'admin_order_edit.html', {"form": form})

def admin_weeklist(request):
    """ 最近一周的报名记录 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    str = ''
    print(info["name"])
    data = models.Admin.objects.filter(username=info["name"]).values()

    today = datetime.today()

    # 计算一周的第一天（假设是周一）
    # 如果今天不是周一，那么找到距离今天最近的周一
    # 使用weekday()函数，周一返回0，周日返回6
    delta = today.weekday()
    first_day_of_week = today - timedelta(days=delta)
    for d in data:
        print(d['gname'])
        str = d["gname"]
    queryset = models.Order.objects.filter(order_date__gte=first_day_of_week,gname=str) # 查所有报名信息
    print(queryset)
    page_object = Pagination(request, queryset, page_size=5)  # 添加分页功能肄业5条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "admin_week_orderlist.html", context)

def admin_monthlist(request):
    """ 最近一个月的报名记录 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    str = ''
    print(info["name"])
    data = models.Admin.objects.filter(username=info["name"]).values()
    # 获取当前日期
    today = datetime.today()

    # 获取当前月份的第一天
    # 创建一个新的datetime对象，但将日期部分设置为1
    first_day_of_month = datetime(today.year, today.month, 1)
    for d in data:
        str = d["gname"]
    queryset = models.Order.objects.filter(order_date__gte=first_day_of_month, gname=str)  # 查所有商品信息
    print(queryset)
    page_object = Pagination(request, queryset, page_size=5)  # 添加分页功能肄业5条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "admin_month_orderlist.html", context)

def admin_yearlist(request):
    """ 最近半年的报名记录 """
    info = request.session.get("info")
    if not info:
        return redirect('/adminlogin/')
    str = ''
    print(info["name"])
    data = models.Admin.objects.filter(username=info["name"]).values()
    # 获取当前日期
    today = datetime.today()

    # 减去5个月，并将日期设置为1号（得到最近六个月中第一个月的第一天）
    first_day_of_six_months_ago = (today - timedelta(days=30 * 5)).replace(day=1)
    for d in data:
        str = d["gname"]
    queryset = models.Order.objects.filter(order_date__gte=first_day_of_six_months_ago, gname=str)  # 查所有商品信息
    print(queryset)
    page_object = Pagination(request, queryset, page_size=5)  # 添加分页功能肄业5条记录
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
    }
    return render(request, "admin_year_orderlist.html", context)